﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using RoadFlow.Utility;

namespace RoadFlow.IntegrateCore.Areas.RoadFlowCore.Controllers
{
    [Area("RoadFlowCore")]
    public class FlowEntrustController : Controller
    {
        [Validate]
        public IActionResult Index()
        {
            ViewData["appId"] = Request.Querys("appid");
            ViewData["tabId"] = Request.Querys("tabid");
            ViewData["isOneSelf"] = Request.Querys("isoneself");
            ViewData["query"] = "appid="+ Request.Querys("appid") + "&tabid="+ Request.Querys("tabid") + "&isoneself="+ Request.Querys("isoneself"); 
            return View();
        }
        [Validate]
        public string Query()
        {
            string UserID = Request.Forms("UserID");
            string Date1 = Request.Forms("Date1");
            string Date2 = Request.Forms("Date2");
            string sidx = Request.Forms("sidx");
            string sord = Request.Forms("sord");
            string isoneself = Request.Querys("isoneself");

            int size = Tools.GetPageSize();
            int number = Tools.GetPageNumber();
            bool isAsc = "asc".EqualsIgnoreCase(sord);
            string order = (sidx.IsNullOrEmpty() ? "WriteTime" : sidx) + " " + (sord.IsNullOrEmpty() ? "DESC" : sord);
            Guid userId = "1".Equals(isoneself) ? Current.UserId : new Business.User().GetUserId(UserID);
            var flowEntrusts = new Business.FlowEntrust().GetPagerList(out int count, size, number, userId.IsEmptyGuid() ? "" : userId.ToString(), Date1, Date2, order);
            Newtonsoft.Json.Linq.JArray jArray = new Newtonsoft.Json.Linq.JArray();
            Business.User user = new Business.User();

            Business.Flow flow = new Business.Flow();
            foreach (System.Data.DataRow dr in flowEntrusts.Rows)
            {
                string status = string.Empty;
                DateTime startTime = dr["StartTime"].ToString().ToDateTime();
                DateTime endTime = dr["EndTime"].ToString().ToDateTime();
                DateTime now = DateExtensions.Now;
                if (startTime >= now)
                {
                    status = "<span>未开始</span>";
                }
                else if (endTime <= now)
                {
                    status = "<span style=\"color:#666;\">已结束</span>";
                }
                else
                {
                    status = "<span style=\"color:green;font-weight:bold;\">委托中</span>";
                }
                Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject
                {
                    { "id", dr["Id"].ToString() },
                    { "UserID", user.GetName(dr["UserID"].ToString().ToGuid()) },
                    { "ToUserID", user.GetNames(dr["ToUserID"].ToString()) },
                    { "FlowID", !dr["FlowID"].ToString().IsGuid(out Guid fid) ? "全部流程" : flow.GetName(fid) },
                    { "WriteTime", dr["WriteTime"].ToString().ToDateTime().ToDateTimeString() },
                    { "StartTime", startTime.ToDateTimeString() },
                    { "EndTime", endTime.ToDateTimeString() },
                    { "Note", dr["Note"].ToString() },
                    { "Status", status },
                    { "Opation", "<a class=\"list\" href=\"javascript:void(0);\" onclick=\"add('" + dr["Id"].ToString() + "');return false;\"><i class=\"fa fa-edit (alias)\"></i>编辑</a>" }
                };
                jArray.Add(jObject);
            }
            return "{\"userdata\":{\"total\":" + count + ",\"pagesize\":" + size + ",\"pagenumber\":" + number + "},\"rows\":" + jArray.ToString() + "}";
        }
        [Validate]
        public IActionResult Edit()
        {
            string entrustid = Request.Querys("entrustid");
            Model.FlowEntrust flowEntrustModel = null;
            if (entrustid.IsGuid(out Guid guid))
            {
                flowEntrustModel = new Business.FlowEntrust().Get(guid);
            }
            if (null == flowEntrustModel)
            {
                flowEntrustModel = new Model.FlowEntrust
                {
                    Id = Guid.NewGuid(),
                    StartTime = DateExtensions.Now,
                    WriteTime = DateExtensions.Now
                };
                if ("1".Equals(Request.Querys("isoneself")))
                {
                    flowEntrustModel.UserId = Current.UserId;
                }
            }
            ViewData["isAdd"] = Request.Querys("entrustid").ToString().IsNullOrWhiteSpace();
            ViewData["isOneSelf"] = Request.Querys("isoneself");
            ViewData["queryString"] = Request.UrlQuery();
            ViewData["pageSize"] = Request.Querys("pagesize");
            ViewData["pageNumber"] = Request.Querys("pagenumber");
            ViewData["flowOptions"] = new Business.Flow().GetOptions(flowEntrustModel.FlowId.ToString());
            return View(flowEntrustModel);
        }
        [Validate]
        [ValidateAntiForgeryToken]
        public string Save(Model.FlowEntrust flowEntrustModel)
        {
            flowEntrustModel.UserId = new Business.User().GetUserId(Request.Forms("UserId").ToString());
            Business.FlowEntrust flowEntrust = new Business.FlowEntrust();
            if (Request.Querys("entrustid").IsGuid(out Guid guid))
            {
                var oldModel = flowEntrust.Get(guid);
                string oldJSON = null == oldModel ? "" : oldModel.ToString();
                flowEntrust.Update(flowEntrustModel);
                Business.Log.Add("修改了流程委托-" + flowEntrustModel.Id, type: Business.Log.Type.流程管理, oldContents: oldJSON, newContents: flowEntrustModel.ToString());
            }
            else
            {
                flowEntrust.Add(flowEntrustModel);
                Business.Log.Add("添加了流程委托-" + flowEntrustModel.Id, flowEntrustModel.ToString(), Business.Log.Type.流程管理);
            }
            return "保存成功!";
        }
        [Validate]
        [ValidateAntiForgeryToken]
        public string Delete()
        {
            string ids = Request.Forms("ids");
            List<Model.FlowEntrust> flowEntrusts = new List<Model.FlowEntrust>();
            Business.FlowEntrust flowEntrust = new Business.FlowEntrust();
            foreach (string id in ids.Split(','))
            {
                if (!id.IsGuid(out Guid eid))
                {
                    continue;
                }
                var model = flowEntrust.Get(eid);
                if (null != model)
                {
                    flowEntrusts.Add(model);
                }
            }
            int i = flowEntrust.Delete(flowEntrusts.ToArray());
            Business.Log.Add("删除了流程委托", Newtonsoft.Json.JsonConvert.SerializeObject(flowEntrusts), Business.Log.Type.流程管理);
            return "删除成功!";
        }
    }
}